package com.xiaomaoguai.fcp.fcp.aop;

import com.xiaomaoguai.fcp.fcp.dto.ResponseModel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.StopWatch;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;

import java.util.concurrent.TimeUnit;

/**
 * 统一异常处理
 *
 * @fileName: ControllerAOP.java
 * @author: WeiHui
 * @date: 2018/8/14 18:00
 * @version: v1.0.0
 * @since JDK 1.8
 */
@Slf4j
//@Aspect
//@Component
public class ControllerAOP {

	/**
	 * 切面处理
	 *
	 * @param pjp join point
	 * @return data
	 */
	@Around("execution (* com.xiaomaoguai.fcp.controller.*.*(..))")
	public Object handlerControllerMethod(ProceedingJoinPoint pjp) {
		StopWatch watch = new StopWatch();
		watch.start();
		ResponseModel<?> result;
		//RequestAttributes ra = RequestContextHolder.getRequestAttributes();
		//ServletRequestAttributes sra = (ServletRequestAttributes) ra;
		//HttpServletRequest request = sra.getRequest();
		try {
			result = (ResponseModel<?>) pjp.proceed();
			watch.stop();
			long time = watch.getTime(TimeUnit.MILLISECONDS);
			log.info("{} use time: [{}] ms", pjp.getSignature(), time);
		} catch (Throwable e) {
			result = handlerException(pjp, e);
		}
		return result;
	}

	/**
	 * @param pjp join point
	 * @param e   ex
	 * @return data
	 */
	private ResponseModel<?> handlerException(ProceedingJoinPoint pjp, Throwable e) {
		log.error(pjp.getSignature() + " error ", e);
		ResponseModel<?> result = new ResponseModel<>();
		result.setCode(9999);
		result.setMsg(e.getMessage());
		return result;
	}
}
